import { getCurrentInstance, ref } from "vue";
import { getParamByParentIdList, getDict as getDictFn } from "@/api/modules/sys";

// 获取字典数据
const getDicList = async (params: any) => {
  const { data } = await getParamByParentIdList(params);
  return data || [];
};

export const useDict = (arr?: string[]) => {
  let resolve;
  const promise = new Promise(res => {
    resolve = res;
    // reject = rej;
  });
  // let { promise, resolve } = Promise.withResolvers();

  let dictList = ref({});
  const cxt = getCurrentInstance();
  const dict = cxt?.appContext.config.globalProperties.$dict;

  if (arr && arr.length) {
    getDicList({ parentIdList: arr.map(item => dict[item] || item).join(",") }).then(res => {
      dictList.value = res;
      resolve(res);
    });
  }

  // 获取字典数据
  const getDict = (key: string) => {
    return dictList.value[dict[key] || key];
  };
  // 获取字典单项id
  const getDictItem = (key: string, value: string) => {
    const result = dictList.value[dict[key] || key]?.find((item: any) => item.id == value);
    return (result && result.name) || "--";
  };
  // 异步获取字典数据
  const getDictAsync = async (key: string) => {
    return getDictFn({ parentId: dict[key] });
  };
  const getDictIdAsync = async (id: string) => {
    const { data } = await getDictFn({ parentId: id });
    return data || [];
  };
  // 获取字典单项id
  const getDictId = (key: string) => {
    return dict[key];
  };
  // 根据id获取key
  const getParentIdKey = (id: string) => {
    return Object.keys(dict).find(item => dict[item] == id);
  };
  // 传入key 的list
  const getDictKeyList = async (arr: string[]) => {
    const { data } = await getDicList({ parentIdList: arr.map(item => dict[item]).join(",") });
    return data;
  };

  return {
    getDict,
    getDictItem,
    getDictIdAsync,
    getDictAsync,
    getDictId,
    getDicList,
    dict,
    getParentIdKey,
    promise,
    getDictKeyList
  };
};
